package cn.ug.login.service.impl;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.config.CacheUtilsService;
import cn.ug.core.SerializeObjectError;
import cn.ug.login.bean.type.VerificationCodeType;
import cn.ug.login.service.VerificationCodeService;
import cn.ug.service.impl.BaseServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * 验证码服务
 *
 * @author kaiwotech
 */
@Service
public class VerificationCodeServiceImpl extends BaseServiceImpl implements VerificationCodeService {
    private static final String TYPE_NAME = VerificationCodeServiceImpl.class.getTypeName();

    /**
     * 最大保存时间（单位秒）
     */
    private static final long MAX_ACTIVE_SECONDS = 5 * 60;

    @Resource
    private CacheUtilsService cacheUtilsService;

    @Value("${spring.cloud.config.profile}")
    private String environMent;

    private static final String VERIFY_CODE = "123456";

    @Override
    public String put(VerificationCodeType type, String key) {
        int min = 100001;
        int max = 999999;
        Random random = new Random();
        Integer code = random.nextInt(max) % (max - min + 1) + min;
        String value = code.toString();

        cacheUtilsService.setCache(TYPE_NAME, getKey(type, key), value, MAX_ACTIVE_SECONDS, TimeUnit.SECONDS);
        return value;
    }

    @Override
    public String get(VerificationCodeType type, String key) {
        Object obj = cacheUtilsService.getCache(TYPE_NAME, getKey(type, key));
        if (null == obj) {
            return null;
        }
        // 移除key
//		cacheUtilsService.deleteCache(TYPE_NAME, key);
        return obj.toString();
    }

    @Override
    public boolean check(VerificationCodeType type, String key, String code) {
        if (StringUtils.isBlank(code)) {
            return false;
        }
       /* if (!environMent.equalsIgnoreCase("beta")) {
            if (VERIFY_CODE.equalsIgnoreCase(code)) {
                return true;
            } else {
                return false;
            }
        }*/
        String cacheCode = get(type, key);
        boolean isOk = code.equals(cacheCode);
        if (isOk) {
            // TODO 验证成功后是否要移除验证码
        }
        return isOk;
    }

    /**
     * 生成Key
     *
     * @param type 类型
     * @param key  主键
     * @return 新的主键
     */
    private String getKey(VerificationCodeType type, String key) {
        return type.toString() + ":" + key;
    }
}

